#!/usr/bin/env python
#coding: utf-8
'''
Created on 2017年3月8日

@author: Administrator
'''
from common.decorators import login_required
from django.db.models.query_utils import Q
from django.db.utils import IntegrityError
from django.http.response import HttpResponse
from django.template.response import TemplateResponse
from funcresource import settings
from funcresource.decorators import user_funcresource
from funcresource.models import Functional, UserFunctional
import copy
import ujson as json


@login_required
@user_funcresource
def index(request, template="funcresource/admin/functional/functional.html"):
    rsp_data = copy.copy(settings.ERROR["SUCC"])
    return TemplateResponse(request, template, rsp_data)
    
@login_required
def list(request):
    rsp_data = copy.copy(settings.ERROR["SUCC"])
    rsp_data["data"] = []
    start = int(request.POST['start'])
    length = int(request.POST['length'])
    keyword = request.POST["search[value]"]
    state = request.POST["columns[5][search][value]"]
    state = '' if state == '' else state[1:-1]
    draw = request.POST['draw']
    q = Q()
    if keyword:
        q.add(Q(**{"func_resource__name__icontains": keyword}), Q.OR)
        q.add(Q(**{"name__icontains": keyword}), Q.OR)
    if state:
        q.add(Q(**{"state": state}), Q.AND)
    count = Functional.objects.filter(q).count()
    functionals = Functional.objects.filter(q)[start:start + length]
    for functional in functionals:
        record = {
            "id":functional.id,
            "name":functional.name,
            "label_css":functional.label_css,
            "remark":functional.remark,
            "state":functional.state,
            "icon_id":functional.icon.id if functional.icon else "",
            "state_desc":settings.get_state_desc(functional.state),
            "func_resource_name":functional.func_resource.name if functional.func_resource else "",
            "func_resource_id":functional.func_resource.id if functional.func_resource else "",
        }
        rsp_data["data"].append(record)
    rsp_data["recordsTotal"] = count
    rsp_data["recordsFiltered"] = count
    rsp_data["draw"] = draw
    return HttpResponse(json.dumps(rsp_data), mimetype='application/json')
@login_required
def save(request):
    rsp_data = copy.copy(settings.ERROR["SUCC"])
    id = request.POST.get("func_id", "")
    name = request.POST["name"]
    icon_id = request.POST["icon_id"]
    func_resource_id = request.POST["func_resource_id"]
    remark = request.POST["remark"]
    css_class = request.POST["css_class"]
    if id:
        try:
            func = Functional.objects.get(id=id)
        except Functional.DoesNotExist:
            rsp_data = copy.copy(settings.ERROR["NOT_EXIST_ERR"])
            return HttpResponse(json.dumps(rsp_data), mimetype='application/json')
    else:
        func = Functional()
    func.name = name
    func.remark = remark
    func.label_css = css_class
    func.func_resource_id = func_resource_id
    if icon_id:
        func.icon_id = icon_id
    try:
        func.save()
    except IntegrityError:
        rsp_data = copy.copy(settings.ERROR["EXIST_ERR"])
        rsp_data["msg"] = u"标签class已经存在"
        return HttpResponse(json.dumps(rsp_data), mimetype='application/json')
    return HttpResponse(json.dumps(rsp_data), mimetype='application/json')

@login_required
def delete(request):
    """
        func:
                                删除
        parameters:
            functional_ids:id集合
    """
    rsp_data = copy.copy(settings.ERROR["SUCC"])
    #获取并赋值
    functional_ids = request.POST["functional_ids"]
    if functional_ids:
        functional_ids = functional_ids.split(",")
    UserFunctional.objects.filter(func__id__in=functional_ids, state=settings.StateEnum.VALID).update(state=settings.StateEnum.DELETED)
    Functional.objects.filter(id__in=functional_ids, state=settings.StateEnum.VALID).update(state=settings.StateEnum.DELETED)
    return HttpResponse(json.dumps(rsp_data), mimetype='application/json')

@login_required
def reopen(request):
    """
        func:
                                重新开通
        parameters:
            functional_ids:id集合
    """
    rsp_data = copy.copy(settings.ERROR["SUCC"])
    #获取并赋值
    functional_ids = request.POST["functional_ids"]
    if functional_ids:
        functional_ids = functional_ids.split(",")
    Functional.objects.filter(id__in=functional_ids, state=settings.StateEnum.DELETED).update(state=settings.StateEnum.VALID)
    return HttpResponse(json.dumps(rsp_data), mimetype='application/json')

